package com.example.myapplication123;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView tex;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button) findViewById(R.id.button1);
        tex=(TextView) findViewById(R.id.text1);
        button.setOnClickListener(this);
    }
    public void onClick(View v){
        if(v.getId()==R.id.button1){
            sendRequestWithOkHttp();
        }
    }
    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client=new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://weather.com/zh-CN/weather/today/l/CHXX0008:1:CH?Goto=Redirected")
                            .build();
                    //调用newCall方法创建一个Call对象，并调用它的execute方法发送请求获取服务器返回的数据
                    Response response = client.newCall(request).execute();
                    //返回的具体内容
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行UI操作，将结果显示到界面上
                tex.setText(response);
            }
        });
    }
}